package com.woniu.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import com.woniu.entity.CreUser;
import com.woniu.service.CreditUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户管理控制
 */
@Api("用户信息管理")
@RestController
@RequestMapping("/credit/creUser")
public class CreditUserController extends BaseController {


    @Autowired
    private CreditUserService creditUserService;


    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private TokenService tokenService;


    @Autowired
    private ISysUserService userService;

    /**
     * 获取用户列表
     * author：李敬
     */
    @ApiOperation("获取用户列表")
    @GetMapping("/list")
    public TableDataInfo list(CreUser user) {
        startPage();
        List<CreUser> list = creditUserService.selectUserList(user);
        return getDataTable(list);
    }

    //author：李敬
    @ApiOperation("用户信息修改")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/update")
    public AjaxResult edit(@Validated @RequestBody CreUser user) {
//        creditUserService.checkUserAllowed(user);
//        creditUserService.checkUserDataScope(user.getUserId());
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(creditUserService.checkPhoneUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(creditUserService.checkEmailUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        return toAjax(creditUserService.updateUser(user));
    }


    /**
     * 根据用户编号获取详细信息
     *
     * @param userId
     * @return
     */
    @ApiOperation("用户编号获取详细信息")
    @GetMapping("/userDetail/{userId}")
    @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "Long", paramType = "path", dataTypeClass = Long.class)
    public AjaxResult getUserDetail(@PathVariable(value = "userId", required = false) Long userId) {
        creditUserService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            CreUser creUser = creditUserService.selectUserDetById(userId);
            ajax.put(AjaxResult.DATA_TAG, creUser);

//            ajax.put("postIds", postService.selectPostListByUserId(userId));

            ajax.put("roleIds", creUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }
//author：李敬 初次贷款查询
@ApiOperation("初次贷款查询")
    @GetMapping("/selectLoanUser")
    public AjaxResult selectLoanUser() {
        AjaxResult ajax = AjaxResult.success();
         List<CreUser> list=creditUserService.selectLoanUser();
          ajax.put(AjaxResult.DATA_TAG, list);
        return ajax;
    }

    //author：李敬 多次贷款查询
    @ApiOperation("多次贷款查询")
    @GetMapping("/selectLoansUser")
    public AjaxResult selectLoansUser() {
        AjaxResult ajax = AjaxResult.success();
        List<CreUser> list=creditUserService.selectLoansUser();
        ajax.put(AjaxResult.DATA_TAG, list);
        return ajax;
    }

    //author：李敬 首次逾期查询
    @ApiOperation("首次次逾期查询")
    @GetMapping("/selectOutUser")
    public AjaxResult selectOutUser() {
        AjaxResult ajax = AjaxResult.success();
        List<CreUser> list=creditUserService.selectOutUser();
        ajax.put(AjaxResult.DATA_TAG, list);
        return ajax;
    }
    @ApiOperation("多次次逾期查询")
    @GetMapping("/selectOutsUser")
    public AjaxResult selectOutsUser() {
        AjaxResult ajax = AjaxResult.success();
        List<CreUser> list=creditUserService.selectOutsUser();
        ajax.put(AjaxResult.DATA_TAG, list);
        return ajax;
    }
    /**
     * 状态修改，
     * author：李敬
     */
    @ApiOperation("状态修改")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUserStatus(user));
    }


    /**
     * 修改用户详情
     */
    @ApiOperation("修改用户详情")
    @PutMapping("/profile")
    public AjaxResult updateProfile(@RequestBody CreUser user) {
//        LoginUser loginUser = getLoginUser();
//        CreUser creUser = loginUser.getUser();
//        user.setUserName(user.getUserName());
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(creditUserService.checkPhoneUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(creditUserService.checkEmailUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        if (StringUtils.isNotEmpty(user.getIdentityCard())
                && UserConstants.NOT_UNIQUE.equals(creditUserService.checkIdentityCardUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，身份证账号已存在");
        }
        if (StringUtils.isNotEmpty(user.getBankCard())
                && UserConstants.NOT_UNIQUE.equals(creditUserService.checkBankCardUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，银行卡账号已存在");
        }
        if (StringUtils.isNotEmpty(user.getHouseCertificate())
                && UserConstants.NOT_UNIQUE.equals(creditUserService.checkHouseCertificateUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，房权证号已存在");
        }

//        user.setUserId(creUser.getUserId());

        if (creditUserService.updateUserDetailProfile(user) > 0) {
            // 更新缓存用户信息
            user.setRealName(user.getRealName());
            user.setIdentityCard(user.getIdentityCard());
            user.setEducationLevel(user.getEducationLevel());
            user.setBankCard(user.getBankCard());
            user.setOccupation(user.getOccupation());
            user.setMonthIncome(user.getMonthIncome());
            user.setAddress(user.getAddress());
            user.setHouseCertificate(user.getHouseCertificate());
            user.setEmergencyPhone(user.getEmergencyPhone());

//            tokenService.setLoginUser(loginUser);
            return AjaxResult.success();
        }
        return AjaxResult.error("修改个人信息异常，请联系管理员");
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CreUser user) {
        List<CreUser> list = creditUserService.selectUserList(user);
        ExcelUtil<CreUser> util = new ExcelUtil<CreUser>(CreUser.class);
        util.exportExcel(response, list, "用户数据");
    }

}
